﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Medianamik.Core.Interfaces;

namespace Medianamik.Core.Querying
{
    public class OrderedQuery : IQuery
    {
        protected IQuery InnerQuery { get; private set; }
        internal OrderedQuery(IQuery pInnerQuery)
        {
            InnerQuery = pInnerQuery;
        }
        public OrderedQuery ThenBy<TResult>(Expression<Func<IQueryableNode, TResult>> pExpression)
        {
            if (pExpression.Body is MemberExpression)
            {
                InnerQuery.Definition.NodeOrderByCollection.Add(new NodeOrderBy((MemberExpression)pExpression.Body, false));
                return this;
            }
            throw new ArgumentException("Expression body must be a MemberExpression");
        }
        public OrderedQuery ThenByDesc<TResult>(Expression<Func<IQueryableNode, TResult>> pExpression)
        {
            if (pExpression.Body is MemberExpression)
            {
                InnerQuery.Definition.NodeOrderByCollection.Add(new NodeOrderBy((MemberExpression)pExpression.Body, true));
                return this;
            }
            throw new ArgumentException("Expression body must be a MemberExpression");
        }


        public IEnumerable<Node> Execute()
        {
            return InnerQuery.Execute();
        }

        public int Count()
        {
            return InnerQuery.Count();
        }

        public IQuery<T> AsQuery<T>() where T : INodeWrapper, new()
        {
            return InnerQuery.AsQuery<T>();
        }

        #region IQuery Members


        Medianamik.Core.Caching.INodeCacheProvider IQuery.CacheProvider
        {
            get { return InnerQuery.CacheProvider; }
        }

        IQueryDefinition IQuery.Definition
        {
            get { return InnerQuery.Definition; }
        }

        #endregion


    }
}
